<script lang="ts" setup>
import { onMounted, ref, reactive } from 'vue';
import { getCurrentInstance, showLoading, showToast, navigateBack } from '@tarojs/taro';
import dayjs from 'dayjs';
import {
  MEETING_INFO_QUERY_APP,
  MEETING_INFO_APPOINTMENT,
} from '/@/api/modules/meeting/meeting-info';
import { MeetingFormState } from './index.d';
import { formRules, state } from './state';
import { meetingRoomUsedStatus } from '/@/common/meeting/meeting-list';
import TimeRangeListSelectorPopup from './components/time-range-list-selector-popup/time-range-list-selector-popup.vue';
import MeetingEditUserTable from './components/meeting-edit-user-table.vue';
import { MeetingUser } from './index.d';
/**
 * 局部要提交的form信息
 */
const formState = reactive<MeetingFormState>({
  userList: [],
  content: '',
  meetingTime: '',
  startTime: 0,
  endTime: 0,
});

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  id: string;
  applyTime: string;
};

const receiveEditFormRef = ref();

/**
 * @function 确认提交
 */
function submit() {
  receiveEditFormRef.value.validate().then(({ valid }: any) => {
    if (!valid) return;
    showLoading({ title: '加载中...' });
    MEETING_INFO_APPOINTMENT({
      meetingId: params.id,
      date: Number(params.applyTime),
      startTime: formState.startTime,
      endTime: formState.endTime,
      theme: formState.content,
      attendUaaUserIds: formState.userList.map((item) => item.uaaUserId).join(','),
    }).then((res) => {
      showToast({
        title: res.comResp?.msg || res.comResp?.tip || '',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            navigateBack();
          }, 2000);
        },
      });
    });
  });
}

onMounted(() => {
  queryDetail();
  state.meetingTime = '';
});

/**
 * 查询会议室详情
 */
function queryDetail() {
  showLoading();
  MEETING_INFO_QUERY_APP({
    comQuery: { page: 1, pageSize: 15 },
    dto: { appointmentTime: Number(params.applyTime), id: params.id },
  }).then((res) => {
    if (!res.dto || !res.dto.length) return;
    state.meetingInfo = { ...res.dto[0], ...meetingRoomUsedStatus(res.dto[0]) };
  });
}

/**
 * 时间区域选择，例如：6:00-6-30
 */
function timeRangeSelected(startTime: number, endTime: number) {
  formState.startTime = startTime;
  formState.endTime = endTime;
  state.meetingTime =
    dayjs(formState.startTime).format('HH:mm') + '-' + dayjs(formState.endTime).format('HH:mm');
}

function changeUser(userList: MeetingUser[]) {
  formState.userList.push(...userList);
}
</script>

<template>
  <view class="meeting-edit app-page--1">
    <app-navbar title="会议预约" />
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="meeting-edit__wrapper">
        <nut-form
          :model-value="formState"
          :rules="formRules"
          class="meeting-edit__form"
          ref="receiveEditFormRef"
          body-align="right"
        >
          <nut-form-item label="预约会议室" prop="meetingRoomName">
            <nut-input
              :model-value="state.meetingInfo.name"
              :border="false"
              readonly
              input-align="right"
            />
          </nut-form-item>
          <nut-form-item label="申请日期" prop="meetingDate">
            <nut-input
              :model-value="dayjs(Number(params.applyTime)).format('YYYY-MM-DD')"
              :border="false"
              readonly
              input-align="right"
            />
          </nut-form-item>
          <nut-form-item
            prop="startTime"
            label="会议时间"
            required
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="state.meetingTime"
              placeholder="请选择开始时间"
              :border="false"
              readonly
              input-align="right"
              @click-input="state.appTimeRangePopupIsShow = !state.appTimeRangePopupIsShow"
            />
          </nut-form-item>
          <nut-form-item
            required
            prop="content"
            label="会议内容"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              v-model="formState.content"
              placeholder="请输入会议内容"
              :border="false"
              input-align="right"
            />
          </nut-form-item>
          <nut-form-item
            required
            prop="userList"
            label-width="0"
            label-align="left"
            error-message-align="left"
          >
            <meeting-edit-user-table @on-change="changeUser" />
          </nut-form-item>
        </nut-form>
      </view>
    </scroll-view>

    <view class="meeting-edit__footer">
      <nut-button block type="info" @click="submit">
        <text>提交</text>
      </nut-button>
    </view>
    <time-range-list-selector-popup
      v-model="state.appTimeRangePopupIsShow"
      :timestamp="Number(params.applyTime)"
      :is-full-room="state.meetingInfo.isFullRoom"
      @on-selected="timeRangeSelected"
    />
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
